<template>
  <view class="container">
    <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ native: true }" @down="downCallback" :up="upOption"
      @up="upCallback">
	  <view class="live-bg">
	  	<view class="live-list">
			<view class="live-item-" v-for="(item,index) in courseLists" :key="item.id" @click="goCourses(item)">
				<!-- <image class="live-image" src="/static/img/pic.jpg" mode="widthFix"></image> -->
				<!-- <image class="live-image" :src="getImgUrl(item.thumbnail)" mode="aspectFill"></image> -->
				<image class="live-image" :src="item.thumbnail" mode="aspectFill" v-if="item.status == 20"></image>
				<image class="live-image" :src="getImgUrl(item.thumbnail)" v-else mode="aspectFill"></image>
				<view class="live-title"><view>录播</view>：{{item.title}}</view>
				<!-- <view class="live-time">时间：{{ formatTime(item.last_time) }}</view> -->
				<view class="live-icon-play">
					<!-- <u-icon name="play-circle" size="70" :color="'#fff'"></u-icon> -->
					<image class="live-icon-image" src="/static/img/bfq-icon.png" mode="aspectFill"></image>
				</view>
				<view class="expire_time" v-if="item.isShowAirtime && item.expire_time > 0">
				    <u-icon name="lock" color="#12a15c" size="40" style="margin-bottom: 10rpx;margin-top: 12rpx;"></u-icon>
				    <u-count-down separator-size="26" color="#12a15c" :height="30" :timestamp="item.expire_time" @end="handleEnd2(index,item)"></u-count-down>
				</view>
			</view>
			<view class="live-item-" v-for="(item,index) in liveLists" :key="item.id" @click="goLive(item)">
				<!-- <image class="live-image" src="/static/img/pic.jpg" mode="widthFix"></image> -->
				<!-- <image class="live-image" :src="getImgUrl(item.thumbnail)" mode="aspectFill"></image> -->
				<image class="live-image" :src="item.thumbnail" mode="aspectFill" v-if="item.status == 20"></image>
				<image class="live-image" :src="getImgUrl(item.thumbnail)" v-else mode="aspectFill"></image>
				<view class="live-tag">
					<u-tag :text="item.permission == 10 ? '所有人' : item.permission == 20 ? '会员' : '-'" mode="light" type="success" size="mini" />
				</view>
				<view class="live-title"><view>直播中</view>：{{item.title}}</view>
				<!-- <view class="live-time">时间：{{ formatTime(item.last_time) }}</view> -->
				<view class="time-item"  v-if="item.isShowAirtime && item.countdown >= 0 && item.status == 40">
					<view>倒计时：</view>
					<u-count-down :timestamp="item.countdown" separator-size="26" color="#f50" :height="30" @end="handleEnd(index,item)"></u-count-down>
				</view>
				<view class="live-icon-play">
					<!-- <u-icon name="play-circle" size="70" :color="'#fff'"></u-icon> -->
					<image class="live-icon-image" src="/static/img/bfq-icon.png" mode="aspectFill"></image>
				</view>
			</view>
	  	</view>
	  </view>
   </mescroll-body>
  </view>
</template>

<script>
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import SettingModel from '@/common/model/Setting'
  import * as CategoryApi from '@/api/category'
  import Search from '@/components/search'
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import { timestampChangDate, ImgUrlPrefix } from '@/utils/util.js'
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import * as LiveApi from '@/api/live'
  import * as FindApi from '@/api/find'
  // 最后一次刷新时间
  let lastRefreshTime;
  // 每页记录数量
  const pageSize = 15
  export default {
    mixins: [MescrollMixin],
    components: {
      Search,
    },
    data() {
      return {
        // 正在加载中
        isLoading: true,
		// 上拉加载配置
		upOption: {
		  // 首次自动执行
		  auto: true,
		  // 每页数据的数量; 默认10
		  page: { size: pageSize },
		  // 数量要大于4条才显示无更多数据
		  noMoreSize: 4,
		  // 空布局
		  empty: {
		    tip: '暂无数据'
		  }
		},
		// 直播列表数据
		list: {
			data: []
		},
		course_list: [],
		airtime: -1, // 倒计时间
		isShowAirtime: true // 是否显示倒计时间
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
      // 加载页面数据
      this.onRefreshPage()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 每间隔5分钟自动刷新一次页面数据
      const curTime = new Date().getTime()
      if ((curTime - lastRefreshTime) > 5 * 60 * 1000) {
        this.onRefreshPage()
      }
	  this.getCourseList()
    },
	computed:{
		liveLists() {
		  return this.list.data.map(item => {
			   return { ...item, countdown: item.status_at ? this.get_expire_time(item.status_at) : -1, isShowAirtime: true }
		  })
		},
		 
		courseLists() {
		   return this.course_list.map(item => {
		 	   return { ...item, expire_time: item.expire_time ? this.get_expire_time(item.expire_time) : -1, isShowAirtime: true }
		   })
		} 
	},
    methods: {
	  // 转换时间戳
	  formatTime (data) {
	  	const currTime = timestampChangDate('YYYY-mm-dd', data * 1000)
		return currTime
	  },
      // 刷新页面
      onRefreshPage() {
        // 记录刷新时间
        lastRefreshTime = new Date().getTime()
        // 获取页面数据
        // this.getPageData()
      },

      // 获取页面数据
      getPageData() {
        const app = this
        app.isLoading = true
        Promise.all([
            // 获取分类模板设置
            // 优化建议: 可以将此处的false改为true 启用缓存
            SettingModel.data(false),
            // 获取分类列表
            CategoryApi.list()
          ])
          .then(result => {
            // 初始化分类模板设置
            app.initSetting(result[0])
            // 初始化分类列表数据
            app.initCategory(result[1])
          })
          .finally(() => app.isLoading = false)
      },
	  
       /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
	    console.log(page)
        const app = this
		app.list.data = []
        // 设置列表数据
        app.getLiveList(page.num)
          .then(list => {
            const curPageLen = list.items.length
            const totalSize = list.total
            // app.mescroll.endBySize(curPageLen, totalSize)
			app.mescroll.endBySize(4, 4)
          })
          .catch(() => app.mescroll.endErr())
      },
	  
	  // 直播列表
	  getLiveList(pageNo =1) {
		const app = this
		return new Promise((resolve, reject) => {
		 LiveApi.liveList({ page: pageNo }, { load: false })
		    .then(result => {
		      // 合并新数据
		      const newList = result.data
			 //  app.list.data = [{
				// 	id: 1, 
				// 	thumbnail: '/static/img/live_img.png',
				// 	title: '三维游戏场景手绘课程第二节',
				// 	status: 20,
				// 	permission: 10
				// },
				// {
				// 	id: 2, 
				// 	thumbnail: '/static/img/live_img2.jpg',
				// 	title: '水墨风格手绘课程刘老师教学',
				// 	status: 20,
				// 	permission: 10
				// },
				// {
				// 	id: 3, 
				// 	thumbnail: '/static/img/live_img3.png',
				// 	title: '影视CG手绘课程张老师第6节课',
				// 	status: 20,
				// 	permission: 10
				// },
				// {
				// 	id: 4, 
				// 	thumbnail: '/static/img/live_img4.png',
				// 	title: '汽车模型手绘课程三',
				// 	status: 20,
				// 	permission: 10
				// }]
		      app.list.data = getMoreListData(newList, app.list, pageNo)
			  // app.list.data = app.list.data.concat(newList.items)
		      resolve(newList)
		    })
		})
	  },
	  
	  // 课程列表
	  getCourseList(pageNo =1) {
	  		const app = this
	  		FindApi.courseList({ page: pageNo }, { load: false })
			.then(result => {
				if(result.data.items.length > 0) {
					app.course_list = result.data.items.filter((item,index) => index < 4)
				} else {
					app.course_list = []
				}
			  
			})
	  },
      /**
       * 初始化分类模板设置
       * @param {Object} result
       */
      initSetting(setting) {
        this.setting = setting[SettingKeyEnum.PAGE_CATEGORY_TEMPLATE.value]
      },

      /**
       * 初始化分类列表数据
       * @param {Object} result
       */
      initCategory(result) {
        this.list = result.data.list
      },
       // 跳转直播页
	   goLive(val) {
		   console.log(val)
		   this.$navTo('pages/live/liveStreaming', { id:val.id, thumbnail: val.thumbnail })
	   },
	   // 跳转课程详情页
	   goCourses(val){
		  const app = this
		  if(val.expire_time <= 0){
			 this.$navTo('pages/course/course', { id: val.id, name: val.title, thumbnail: val.thumbnail  })
		  } else {
			app.$toast('锁定时间无法进入')
		  }
	   },
	   get_expire_time: function(val) {
	   		const date = new Date().getTime();
	   		if(val) {
	   			let time = val * 1000 - date
	   			console.log(date,time)
	   			return time
	   		} else {
	   			return ''
	   		}
	   },
	   // 倒计时结束事件
	   handleEnd(index, val) {
		  console.log('倒计时结束')
		  this.isShowAirtime = false
		  this.list.data[index].isShowAirtime = false
	   },
	   
	   // 课程倒计时结束事件
	   handleEnd2(index, val) {
		   console.log('倒计时结束')
		   this.course_list[index].isShowAirtime = false
	   },
	   // 图片地址拼接
	   getImgUrl(val) {
		  const url = ImgUrlPrefix(val)
		  return url
	   },
    },

    /**
     * 设置分享内容
     */
    onShareAppMessage() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/live/index?' + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/live/index?' + app.$getShareUrlParams()
      }
    }

  }
</script>

<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
  .live-bg{
  	  background-color: #f3f7f8;
  	  // padding: 16rpx 0;
  	  .live-list{
  	  	  display: flex;
  	  	  flex-wrap: wrap;
  	  	  justify-content: space-between;
  	  	  padding: 30rpx 40rpx 10rpx 40rpx;
  		  background-color: #fff;
  	  	  .live-item-{
  	  		  max-width: 48%;
  	  		  flex: 0 0 50%;
  	  		  color: #666;
  	  		  line-height: 54rpx;
			  position: relative;
			  border-radius: 16rpx;
			  margin-bottom: 20rpx;
  	  		  .live-image{
  	  			  width: 100%;
				  max-height: 176rpx;
				  border-radius: 20rpx;
				  background-color: #eef0f5;
  	  		  }
			  .live-tag{
				  position: absolute;
				  top: 6rpx;
				  left:16rpx;
			  }
  	  		  .live-title{
  	  			  color: #12a15c;
				  display: flex;
				  overflow: hidden;
				  text-overflow: ellipsis;
				  white-space: nowrap;
  	  		  }
  	  		  .live-time{
  	  			  
  	  		  }
  	  		  .live-address{
  	  			  white-space: nowrap;
  	  			  overflow: hidden;
  	  			  text-overflow: ellipsis;
  	  		  }
			  .live-icon-play{
				  position: absolute;
				  top: 0;
				  left:0;
				  width: 100%;
				  height: 70%;
				  line-height: 226rpx;
				  text-align: center;
				  border-radius: 20rpx;
				  // background-color: rgba(255,255,255,0.2);
				  .live-icon-image{
					  width: 80rpx;
					  height: 80rpx;
					  text-align: center;
					  opacity: 0.4;
				  }
			  }
			  
			  .expire_time{
				  position: absolute;
				  top: 0;
				  width: 100%;
				  height: 71%;
				  text-align: center;
				  padding-top: 18rpx;
				  border-radius: 16rpx;
				  color: #12a15c;
				  background-color: rgba(0,0,0,0.5);
			  }
			  
			  .time-item{
			  		 // background-color: rgba(0,0,0,0.95);
			  		  position: absolute;
			  		  bottom: 70rpx;
			  		  left: 0;
			  		  width:100%;
			  		  // height: 70%;
			  		  text-align: center;
			  		  color:  #f50;
			  		  // padding-top: 68rpx;
			  		  // line-height: 48rpx;
			  		  // font-size: 30rpx;
			  		 border-radius: 20rpx;
			  		 display: flex;
			  		 align-items: flex-end;
			  		 justify-content: center;
			  		 font-size: 26rpx;
			  }
  	  	  }
  	  }
  }
</style>